const crypto = require('crypto');
module.exports = app =>{
    const { INTEGER, STRING, DATE, ENUM, TEXT } = app.Sequelize;

    const User = app.model.define('user', {
        id: {
          type: INTEGER(20),
          primaryKey: true,
          autoIncrement: true
        },
        number: {
          type: STRING(30),
          allowNull: true,
          defaultValue: '',
          comment: '学号',
          unique: true
        },
        username: {
          type: STRING(30),
          allowNull: true,
          defaultValue: "",
          comment: "用户名",
          unique: true,
        },
        password: {
          type: STRING,
          allowNull: true,
          defaultValue: "",
          comment: "密码",
          set(val) {
            const hmac = crypto.createHash("sha256", app.config.crypto.secret);
            hmac.update(val);
            let hash = hmac.digest("hex");
            this.setDataValue("password", hash);
          },
        },
        openid: {
          type: STRING,
          allowNull: true,
          defaultValue: "",
          comment: "openid",
        },
        gender: {
          type: INTEGER,
          allowNull: true,
          defaultValue: null,
          comment: "性别"
        },
        class_id: {
          type: INTEGER,
          allowNull: true,
          defaultValue: null,
          comment: "班级id"
        },
        phoneNumber: {
          type: STRING,
          allowNull: true,
          defaultValue: null,
          comment: "手机号",
        },
        birthday: {
          type: STRING,
          allowNull: true,
          defaultValue: "",
          comment: "生日",
        },
        avatar: {
          type: STRING,
          allowNull: true,
          defaultValue: "",
          comment: "头像",
        },
        coin: {
          type: INTEGER,
          allowNull: true,
          defaultValue: 0,
          comment: "金币",
        },
        userStatus: {
          type: INTEGER,
          allowNull: false,
          defaultValue: 0,
          comment: "用户状态"
        },
        created_time: {
          type:DATE,
          get(){
             return app.formatTime(this.getDataValue('created_time'))
          }
        },
        updated_time: DATE,
    });

    User.associate = function() {
      app.model.User.hasMany(app.model.Score, { foreignKey: 'user_id' });

     // 与Class存在多对一关系，所以使用belongsTo()
     app.model.User.belongsTo(app.model.Class, {foreignKey: 'class_id', targetKey: 'id'});
     
    // 与Branch存在多对多关系，使用belongsToMany()
      app.model.User.belongsToMany(app.model.Branch, {
        through: app.model.BranchUser,
        foreignKey: 'user_id',
        otherKey: 'branch_id'
    });


    };

    return User;
}